package cn.edu.ctbu.dp01.service;

import cn.edu.ctbu.dp01.dao.teacherRepository;
import cn.edu.ctbu.dp01.entity.teacher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class teacherService {

    @Autowired
    private teacherRepository teacherRepository;

    // 获取所有教师
    public List<teacher> getAll() {
        return (List<teacher>) teacherRepository.findAll();
    }

    // 根据 ID 查找教师
    public teacher findById(Integer id) {
        Optional<teacher> optionalteacher = teacherRepository.findById(id);
        return optionalteacher.orElse(null);
    }

    // 添加教师
    public teacher add(teacher teacher) {
        return teacherRepository.save(teacher);
    }

    // 更新教师
    public teacher update(teacher teacher) {
        if (teacher.getId() != null && teacherRepository.existsById(teacher.getId())) {
            return teacherRepository.save(teacher);
        } else {
            throw new RuntimeException("教师不存在，无法更新！");
        }
    }

    // 删除教师
    public void delete(Integer id) {
        if (teacherRepository.existsById(id)) {
            teacherRepository.deleteById(id);
        } else {
            throw new RuntimeException("教师不存在，无法删除！");
        }
    }
    public List<teacher> findByName(String name) {
        return teacherRepository.findByNameContaining(name); // 通过名字模糊查询
    }
}
